﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PDX.ContextManagement
{
    public class ResolutionManager
    {
        Context Target { get; set; }
        IPropertyResolver Resolver { get; set; }

        public ResolutionManager(Context target, IPropertyResolver resolver)
        {
            this.Target = target;
            this.Resolver = resolver;

            target.DependencyPropertyChanged += target_DependencyPropertyChanged;
        }

        void target_DependencyPropertyChanged(object sender, System.Windows.DependencyPropertyChangedEventArgs e)
        {
            if (e.Property == Context.DeclarationProperty
                || e.Property == Context.DataContextProperty
                || e.Property == Context.OriginalDataContextProperty)
            {
                var dataContext = Target.GetDataContext();
                var declaration = Context.GetDeclaration(Target);
                if (dataContext == null || declaration == null)
                {
                    Target.SetResolution(null);
                }
                else
                {
                    var resolution = Resolver.Resolve(dataContext, declaration);
                    Target.SetResolution(resolution);
                }
            }
        }
    }
}
